<template>
  <div class="home">
    <ul>
      <li v-for="item in messageList">{{ item }}</li>
    </ul>
    <el-input v-model="value" placeholder="请输入" clearable></el-input>
    <el-button type="primary" @click="ok">发送</el-button>
    <el-button type="primary" @click="close">关闭聊天</el-button>
  </div>
</template>

<script setup>
import { ref, } from 'vue';

const ws = new WebSocket('ws://localhost:3000')
ws.addEventListener('open', function (event) {
  console.log('连接成功');
})
const value = ref('')
const ok = () => {
  if (value.value) {
    ws.send(value.value)
    value.value = ''
  }
}

const messageList = ref([])

// 接收服务端传来的消息
ws.addEventListener('message', function (event) {
  // console.log(event.data.type,'22222')
  // messageList.value.push(event.data)
  let data = JSON.parse(event.data)
  // console.log(data.type,'333');
  if (data.type == 2) {
    messageList.value.push(data.message)
  }
})

const close = () => {  //手动关闭连接
  ws.close()
  console.log('关闭聊天');
}

</script>
